package com.lry.basic.algorithm.flow.token;

import java.util.concurrent.atomic.LongAdder;

public class Token {

    //规定桶大小, 以匀速往令牌桶放令牌, 消费者从令牌桶拿令牌，拿到了则执行，否则限流

    private int capacity;

    private int rate;

    private int tokenNum;

    public Token(int capacity, int rate) {
        this.capacity = capacity;
        this.rate = rate;
        start();
    }

    public synchronized boolean acquire(){
        if(tokenNum>0){
            tokenNum--;
            return true;
        }
        return false;
    }

    private void start(){
        new Thread(()->{
            while (true){

                if(tokenNum<capacity){
                    tokenNum++;
                }

                try {
                    Thread.sleep(1000/rate);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }
}
